<template>
  <VTable ref="tableRef" v-bind="tableOptins" class="is--card">
    <template #form="{ form }">
      <XForm :fieldList="fieldList" :formOption="optionsData" :formData="form">
        <template #create_user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            class="w-[200px]"
            placeholder="请输入"
          />
        </template>
      </XForm>
    </template>
    <template #toolbar_btns>
      <div class="w-full" v-if="totalData?.length">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane
            :label="item.state.label"
            :name="item.state.value"
            v-for="(item, index) in totalData"
            :key="index"
          >
            <template #label>
              {{ item?.state?.label }}(<span
                :class="
                  activeName == item.state.value
                    ? 'base-text-color'
                    : 'text-[#999999]'
                "
                >{{ item.quantity }}</span
              >)
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <VActionBar :actions="actions">
        <template #left>
          <div>
            <VTotal
              ref="totalRef"
              :options="[{ title: '合计付款金额', key: 'inAmount' }]"
              :data="totalAmountData"
            />
          </div>
        </template>
      </VActionBar>
    </template>
    <template #operation="{ row }">
      <el-button
        v-if="row.state.value != 2"
        v-hasPermi="[capitalAuthList.payment.payment_detail.other.edit]"
        type="primary"
        link
        @click="handleAdd(row)"
      >
        编辑
      </el-button>
      <el-button
        v-hasPermi="[capitalAuthList.payment.payment_detail.other.audit]"
        type="primary"
        link
        @click="handleAuditRow(row)"
      >
        审核
      </el-button>
      <el-button
        v-hasPermi="[capitalAuthList.payment.payment_detail.other.log]"
        type="primary"
        link
        @click="handleLog(row)"
      >
        日志
      </el-button>
    </template>
  </VTable>
  <VAudit
    v-model="auditVisible"
    title="审核"
    :option="[
      { label: '已审核', value: 2 },
      { label: '审核失败', value: 3 },
    ]"
    url="/payment/review"
    :isRemark="false"
    :ids="auditId"
    method="patch"
    @close="auditId = null"
    @refresh="refresh"
  />
  <Add
    v-model="addVisible"
    :title="addTitle"
    :data="addData"
    :optionsData="optionsData"
    @refresh="refresh"
    @close="addData = null"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script lang="jsx" setup>
import { ElMessage } from "element-plus";
import { getTableSelectRow } from "@/hooks/tools.js";
import { config_name } from "@/config/export.js";
import XForm from "@/components/XForm/index.vue";
import VTotal from "@/components/VTotal";
import {
  overviewPayment,
  getPayment,
  antiCensorshipPayment,
} from "../../api.js";
import Add from "./add/index";
import { transformData } from "@/utils/tools.js";
import tagStatus from "@/components/tagStatus/index.vue";
import { capitalAuthList } from "@/Auth/capital.js";
const { proxy } = getCurrentInstance();
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const totalData = ref([]);
const activeName = ref(0);
const totalAmountData = reactive({
  inAmount: 0,
});
const getSum = async (params) => {
  const { data } = await overviewPayment(params);
  const { stateQuantity, totalAmount } = data || {};
  totalAmountData.inAmount = totalAmount;
  let quantity = stateQuantity?.reduce(
    (total, item) => total + item.quantity,
    0
  );
  let all = [{ state: { value: 0, label: "全部" }, quantity: quantity }];
  if (quantity == 0) {
    totalData.value = all;
  } else {
    let list = [...all, ...stateQuantity];
    totalData.value = list;
  }
};

const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: {
        type: "paymentTime",
        value: [],
        range: false,
      },
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      width: 180,
      fixed: "left",
      field: "id",
    },
    {
      title: "流水单据",
      field: "serialNo",
      width: 135,
    },
    {
      title: "状态",
      slots: {
        default: ({ row }) => {
          return (
            <tagStatus
              code={row?.state}
              type={[
                { label: 1, value: "warning" },
                { label: 2, value: "primary" },
                { label: 3, value: "danger" },
              ]}
            />
          );
        },
      },
      width: 90,
    },
    {
      title: "渠道/银行",
      field: "accountChannelName",
      minWidth: 100,
    },
    {
      title: "账号/卡号",
      field: "account",
      width: 150,
    },
    {
      title: "付款主体",
      field: "accountPrincipal",
      width: 100,
    },
    {
      title: "资金项目",
      width: 100,
      slots: {
        default: ({ row }) => {
          return <div>{row?.fundUse?.label || "-"}</div>;
        },
      },
    },
    {
      title: "付款金额",
      field: "amount",
      width: 120,
    },
    {
      title: "币种",
      field: "currency",
      width: 60,
    },
    {
      title: "汇率",
      field: "exchangeRate",
      width: 100,
    },
    {
      title: "人民币付款金额",
      field: "localAmount",
      width: 120,
    },
    {
      title: "业务部门 ",
      field: "todo",
      width: 100,
    },
    {
      title: "资金说明 ",
      field: "illustrate",
      width: 200,
    },
    {
      title: "备注 ",
      field: "remark",
      width: 200,
    },
    {
      title: "付款时间 ",
      field: "paymentAt",
      width: 170,
    },
    {
      title: "创建人员 ",
      field: "createUser",
      width: 170,
    },
    {
      title: "添加时间 ",
      field: "createdAt",
      width: 170,
    },
    {
      title: "审核人员 ",
      field: "reviewUser",
      width: 170,
    },
    {
      title: "审核时间 ",
      field: "reviewAt",
      width: 170,
    },
    {
      width: 160,
      fixed: "right",
      title: "操作",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        let params = transformData(form);
        getSum(params);
        if (activeName.value != 0) {
          params.state = activeName.value;
        }
        return getPayment({ ...params, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const handleClick = () => {
  tableRef.value.query();
};
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "serialNo",
    type: "input",
    placeholder: "流水单据",
    style: { width: "120px" },
  },
  {
    field: "fundUse",
    type: "select",
    originOption: "payment_fund_use",
    multiple: true,
    options: {
      placeholder: "资金项目",
    },
    style: { width: "200px" },
  },
  {
    field: "principalId",
    originOption: "principalIds",
    type: "select",
    options: {
      placeholder: "付款主体",
    },
    style: { width: "150px" },
  },
  {
    field: "currency",
    type: "select",
    originOption: "currency",
    multiple: true,
    options: {
      placeholder: "币种",
      valueKey: "label",
    },
    style: { width: "200px" },
  },
  {
    field: "user",
    selectStyle: { width: "120px" },
    select: [
      { label: "创建人员", value: "createUser" },
      { label: "审核人员", value: "reviewUser" },
    ],
    slot: "create_user",
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    select: [{ label: "创建时间", value: "createdAt" }],
    select: [{ label: "审核时间", value: "reviewAt" }],
    selectStyle: { width: "130px" },
    itemProps: {
      startPlaceholder: "创建最早时间",
      endPlaceholder: "创建最晚时间",
    },
  },
];
const auditVisible = ref(false);
const auditId = ref(null);
const handleAudit = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  auditId.value = ids;
  auditVisible.value = true;
};
const handleAuditRow = (row) => {
  auditId.value = [row.id];
  auditVisible.value = true;
};
const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (row) => {
  let data = null;
  if (row?.id) {
    data = {
      ...row,
      accountType: row?.accountType?.value,
      accountChannelId: row?.accountChannelId?.toString(),
      accountId: row?.accountId?.toString(),
      fundUse: row?.fundUse?.value,
    };
  }
  addData.value = data || null;
  addTitle.value = data?.id ? "编辑" : "新增";
  addVisible.value = true;
};
const handleUnAudit = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认反审
        <span class="text-[#3366F1] px-[4px]">{ids.length}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await antiCensorshipPayment({ ids });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("反审成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handleImport = () => {};
//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["capital"]["payment"],
    condition,
  });
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: () => handleAdd(null),
    permission: [capitalAuthList.payment.payment_detail.other.add],
  },
  {
    label: "审核",
    type: "primary",
    fn: handleAudit,
    permission: [capitalAuthList.payment.payment_detail.other.audit],
  },
  {
    label: "反审核",
    fn: handleUnAudit,
    permission: [capitalAuthList.payment.payment_detail.other.un_audit],
  },
  {
    label: "导入",
    right: true,
    dkicon: "icon-Download",
    fn: handleImport,
    permission: [capitalAuthList.payment.payment_detail.other.import],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [capitalAuthList.payment.payment_detail.other.export],
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
:deep(.el-tag.el-tag--danger){
  background-color: var(--base-danger-bg)
}
:deep(.el-tag.el-tag--primary){
  background-color: var(--base-primary-bg);
  border-color: var(--base-primary-bg);;
}
:deep(.el-tag.el-tag--warning){
  background-color: var(--base-warning-bg);
  border-color: var(--base-warning-bg);;
}
</style>
